package com.tobeface.sns.infrastructure.mail.defaults;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import com.kissme.lang.Preconditions;
import com.tobeface.sns.infrastructure.mail.EmailService;

/**
 * 
 * @author loudyn
 * 
 */
@Service
public class DefaultEmailService implements EmailService {

	private JavaMailSender mailSender;

	/**
	 * 
	 * @param mailSender
	 */
	@Autowired
	public DefaultEmailService(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	@Override
	public void send(String to, String content) {
		send(to, null, content);
	}

	@Override
	public void send(final String to, final String subject, final String content) {

		Preconditions.hasText(to);
		Preconditions.hasText(content);
		mailSender.send(new MimeMessagePreparator() {

			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
				helper.setTo(to);
				helper.setSubject(subject);
				helper.setText(content, true);
			}

		});
	}

	/**
	 * 
	 * @param to
	 * @param content
	 * @param attachments
	 */
	@Override
	public void send(final String to, final String content, final File... attachments) {
		send(to, null, content, attachments);
	}

	/**
	 * 
	 * @param to
	 * @param subject
	 * @param content
	 * @param attachments
	 */
	@Override
	public void send(final String to, final String subject, final String content, final File... attachments) {
		Preconditions.hasText(to);
		Preconditions.hasText(content);
		mailSender.send(new MimeMessagePreparator() {

			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
				helper.setTo(to);
				helper.setSubject(subject);
				helper.setText(content, true);
				addAttachments(helper, attachments);
			}

		});

	}

	private void addAttachments(MimeMessageHelper helper, File[] attachments) throws MessagingException {
		for (File attachment : attachments) {
			helper.addAttachment(attachment.getName(), attachment);
		}
	}

}
